package edu.cu.cs214.hw9.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 * Defines an abstract controller for our GUI Windows.  The controllers open client sockets, which
 * allow the GUI to communicate with the servers via String messages
 * @author davidzheng
 *
 */
public abstract class AbstractController {

	protected Socket mySocket;
	protected PrintWriter out;
    protected BufferedReader in;
    
    protected JFrame window;
    
    //protected String myName; for unimplemented error message function
    public AbstractController(JFrame window)
    {
    	this.window = window;
    }
    /**
     * Opens a connection to the given host and port
     * @param hostname host
     * @param port port
     */
    protected void openConnection(String hostname, int port)
    {
    	try {
	    	mySocket = new Socket(hostname, port);
			out = new PrintWriter(mySocket.getOutputStream(), true);
	    	in = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    /**
     * Opens a connection to the given port on the local host
     * @param port
     */
    protected void openConnection(int port)
    {
    	try {
	    	mySocket = new Socket("localhost", port);
			out = new PrintWriter(mySocket.getOutputStream(), true);
	    	in = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    /**
     * Closes the connections
     */
    protected void closeConnection()
    {
    	try {
    		if (mySocket.isConnected())
    			mySocket.close();
    		
			out.close();
	    	in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    //I noticed error messages were generic, so i put this in, but was too lazy to replace all error
    //messages.  Delete if unused
    /*
    protected void errorMessage(String message)
    {
    	String type = myName + " Failure";
    	JOptionPane.showMessageDialog(window, message, type, JOptionPane.PLAIN_MESSAGE);
		out.println("END");
		closeConnection();
    }
    */
}
